-------------------------------------------------------------------------------------
-- -*- coding: utf-8 -*-
--
-- @author:
-- @email:    07291@qq.com
-- @date:     2024/11/6
-- @module:   TimerManager
-- @describe:
-- @version:  v1.0
--

-------------------------------------------------------------------------------------

---@class TimerManager
local TimerManager = {}

function TimerManager:add_timer(key, time, callback, isClear, isFirstCall, isLoop)
    if isClear then
        self:remove_timer(key)
    end
    if self.timers[key] then
        print(string.format("计时器:%s 已经存在", key))
        return
    end
    if not time then
        print(string.format("计时器:%s 没有设置初始时间", key))
        return
    end
    self.timers[key] = {}
    local tmpTimer = self.timers[key]
    if isFirstCall then
        if callback then
            callback()
        end
    end
    tmpTimer.defTime = time
    tmpTimer.time = time
    tmpTimer.callback = callback
    tmpTimer.isLoop = isLoop
end

-- 得到计时器时间
function TimerManager:get_time(key)
    if self.timers[key] then
        return self.timers[key].time
    end
    return nil
end

-- 设置计时器默认时间
function TimerManager:set_defTime(key, time)
    if self.timers[key] then
        self.timers[key].defTime = time
    end
end

-- 更新计时器
function TimerManager:update(deltaTime)
    for key, value in pairs(self.timers) do
        value.time = value.time - deltaTime
    end

end

-- 检查所有计时器
function TimerManager:check_all_timer()
    local deleteTimer = {}
    for key, value in pairs(self.timers) do
        if value.time <= 0 then
            if value.callback then
                value.callback()
            end
            if not value.isLoop then
                table.insert(deleteTimer, key)
            else
                value.time = value.defTime
            end
        end
    end
    for _, key in ipairs(deleteTimer) do
        self:remove_timer(key)
    end
end

-- 删除计时器
function TimerManager:remove_timer(key)
    self.timers[key] = nil
end

-- 清除计时器
function TimerManager:clear()
    self.timers = {}
end

-- 创建计时器管理
function TimerManager:new()
    local ret = {}
    self.__index = self
    setmetatable(ret, self)
    return ret
end

return TimerManager